/**
 * 
 */
package com.my.test.testnet.talk;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * create date: 2010-10-22 上午09:22:28
 * @author Angela Tao
 * @version 1.0
 *
 */
public class TalkServer implements ActionListener,Runnable{
	
	private JFrame f = new JFrame("服务器");
	private JTextArea ta = new JTextArea();
	private JScrollPane sp = new JScrollPane(ta);
	private JTextField tf = new JTextField(20);
	private JButton b = new JButton("发送");
	private JPanel p = new JPanel();
	
	private DataInputStream dis;
	private DataOutputStream dos;

	/**
	 * 
	 */
	public TalkServer() {
		// TODO Auto-generated constructor stub
		ta.setEditable(false);
		p.add(tf);
		p.add(b);
		f.add(p,"South");
		f.add(sp);
		
		f.setSize(350, 400);
		f.setLocation(200, 200);
		f.setVisible(true);
		
		b.addActionListener(this);
		
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.connect();
		new Thread(this).start();
		
	}
	
	public void connect(){
		Socket s = null;
		try {
			ServerSocket ss = new ServerSocket(6000);
			s  = ss.accept();
			
			dis = new DataInputStream(s.getInputStream());
			dos = new DataOutputStream(s.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		/*
		finally {
			try {
				if(s != null){
					s.close();
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		*/
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TalkServer();
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		String info = tf.getText();
		tf.setText("");
		ta.append("Server: "+info+"\n");
		
		try {
			dos.writeUTF("Server: "+info);
			dos.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while(true){
				String info = dis.readUTF();
				ta.append(info+"\n");
			}	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
